package com.maxmlr.music.common.util;

import com.maxmlr.music.common.constant.DictConstant;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Random;

public class FileUtil {

    public static void uploadFile(MultipartFile file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        file.transferTo(new File(filePath + fileName));
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static String renameToId(String fileName) {
        StringBuffer sb = new StringBuffer();
        sb.append(DateUtil.getDateTimeStr());
        sb.append(new Random().nextInt(10));
        sb.append(".");
        sb.append(fileName.substring(fileName.lastIndexOf(".") + 1));
        return sb.toString();
    }

    public static String getFilePathByType(DictConstant.FileTypes fileTypes) {
        StringBuffer sb = new StringBuffer();
        sb.append("/files/");
        sb.append(fileTypes.getPath());
        sb.append("/");
        sb.append(DateUtil.getMonthStr());
        sb.append("/");
        return sb.toString();
    }
}
